package com.czwj.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.czwj.annotation.SystemControllerLog;
import com.czwj.entities.Authority;
import com.czwj.entities.DataGridData;
import com.czwj.entities.Level;
import com.czwj.entities.OperateResult;
import com.czwj.entities.PageBean;
import com.czwj.entities.TreeNode;
import com.czwj.entities.UserInfo;
import com.czwj.service.AuthorityService;
import com.czwj.service.LevelService;
import com.czwj.service.TreeNodeService;
import com.czwj.service.UserInfoService;
import com.czwj.util.CipherUtil;
import com.czwj.util.TextUtil;

@Controller
public class UserInfoAction{
	@Resource
	UserInfoService userInfoService;
	
	@Resource
	TreeNodeService treeNodeService;
	
	@Resource
	AuthorityService authorityService;
	
	@Resource
	LevelService levelService;
	
	@RequestMapping(value = "/user",method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<UserInfo> userInfo(HttpServletResponse response,
			@RequestParam(value = "departmentid",required = true) int departmentid,
			@RequestParam(value = "page",required = false) String page,
			@RequestParam(value = "rows",required = false) String rows){
		DataGridData<UserInfo> result = new DataGridData();
		Map<String,Object> map = new HashMap<String,Object>();
		PageBean pageBean = null;
		if(TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)){
			pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		}
		if(pageBean != null){
			map.put("start",pageBean.getStart());
			map.put("size",pageBean.getPageSize());
		}
		map.put("departmentid",departmentid);
		List<UserInfo> list = userInfoService.search(map);
		result.setRows(list);
		result.setTotal(userInfoService.count(map));
		return result;
	}
	
	@RequestMapping(value = "/userSave.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult userSave(@RequestBody UserInfo user,HttpServletRequest request) throws Exception{
		OperateResult result = new OperateResult();
		int count = 0;
		if(user.getId() != null && user.getId() > 0){
			if(user.isSetpwd()){
				user.setPassword(CipherUtil.encrypt(user.getUsername()));
			}
			count = userInfoService.update(user);
		}else{
			if(user.getRoleid()==5){
				List<UserInfo> userInfos = userInfoService.selectbycompanyroleid(user.getCompanyid());
				if(userInfos.size()>0){
					count = 0;
				}else{
					if(TextUtil.isNotEmpty(user.getUsername())){
						user.setPassword(CipherUtil.encrypt(user.getUsername()));
					}
					Subject currentUser = SecurityUtils.getSubject();
					user.setCreaterid(((UserInfo)currentUser.getSession().getAttribute("userInfo")).getId());
					user.setCreatedate(new Date());
					user.setCreateip(request.getRemoteAddr());
					user.setStatus(2);
					count = userInfoService.insert(user);
					int[] list = {11,12,13,14,16,17};
					for(int i:list){
						Authority authority2 = new Authority();
						authority2.setCompanyid(user.getCompanyid());
						authority2.setLevelid(user.getLevelid());
						authority2.setProjectid(i);
						authorityService.insert(authority2);
					}
				}
			}
		}
		result.setSuccess(count > 0);
		return result;
	}
	
	@SystemControllerLog(description = "临时工考勤")
	@RequestMapping(value = "/jobberSave.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult jobberSave(@RequestParam(value = "name",required = false) String name,
			@RequestParam(value = "jobno",required = false) String jobno,
			@RequestParam(value = "idcard",required = false) String idcard,
			@RequestParam(value = "sex",required = false) String sex,
			@RequestParam(value = "mobile",required = false) String mobile,
			@RequestParam(value = "companyid",required = false) Integer companyid,
			@RequestParam(value = "departmentid",required = false) Integer departmentid,
			@RequestParam(value = "projectitemid",required = false) Integer projectitemid,
			@RequestParam(value = "projectitemchildid",required = false) Integer projectitemchildid,
			@RequestParam(value = "salary",required = false) String salary,HttpServletRequest request) throws Exception{
		OperateResult result = new OperateResult();
		Subject currentUser = SecurityUtils.getSubject();
		Integer createrid = ((UserInfo)currentUser.getSession().getAttribute("userInfo")).getId();
		String createip = request.getRemoteAddr();
		int count = userInfoService.insertjobber(name,jobno,idcard,sex,mobile,companyid,departmentid,createrid,createip,
				projectitemid,projectitemchildid,salary);
		result.setSuccess(count > 0);
		return result;
	}
	
	@SystemControllerLog(description = "注册用户")
	@RequestMapping(value = "/userRegister",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult userRegister(@RequestBody UserInfo user) throws Exception{
		OperateResult result = new OperateResult();
		int count = 0;
		user.setPassword(CipherUtil.encrypt(user.getPassword()));
		user.setStatus(1);
		count = userInfoService.insert(user);
		result.setSuccess(count > 0);
		return result;
	}
	
	@SystemControllerLog(description = "禁用用户")
	@RequestMapping(value = "userDelete.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult userDelete(@RequestParam("userid") int id,@RequestParam("status") int status){
		OperateResult result = new OperateResult();
		try{
			Map<String,Object> map = new HashMap<>();
			map.put("id",id);
			map.put("status",status);
			int count = userInfoService.updateStatus(map);
			result.setSuccess(count > 0);
			return result;
		}
		catch(Exception e){
			// TODO: handle exception
			result.setSuccess(false);
			return result;
		}
	}
	
	@RequestMapping(value = "/check/username",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult checkLoginname(@RequestParam(value = "username",required = true) String username,
			@RequestParam(value = "id",required = true) int id){
		OperateResult result = new OperateResult();
		UserInfo user = userInfoService.findByUserName(username);
		if(user == null){
			result.setSuccess(true);
		}else{
			if(user.getId() == id){
				result.setSuccess(true);
			}else{
				result.setSuccess(false);
			}
		}
		return result;
	}
	
	@RequestMapping(value = "/userInfo",method = RequestMethod.GET)
	@ResponseBody
	public UserInfo userInfo(@RequestParam(value = "userid",required = true) int userid){
		return userInfoService.selectByPrimaryKey(userid);
	}
	
	@RequestMapping(value = "/check/mobile",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult checkMobile(@RequestParam(value = "mobile",required = true) String mobile,
			@RequestParam(value = "id",required = true) int id){
		OperateResult result = new OperateResult();
		UserInfo user = userInfoService.searchbymobile(mobile);
		if(user == null){
			result.setSuccess(true);
		}else{
			if(user.getId() == id){
				result.setSuccess(true);
			}else{
				result.setSuccess(false);
			}
		}
		return result;
	}
	
	@SystemControllerLog(description = "修改用户密码")
	@RequestMapping(value = "/editPwd.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult userSave(@RequestParam(value = "userid",required = true) int userid,
			@RequestParam(value = "oldPwd",required = true) String oldPwd,
			@RequestParam(value = "newPwd",required = true) String newPwd) throws Exception{
		OperateResult result = new OperateResult();
		UserInfo userInfo = userInfoService.selectByPrimaryKey(userid);
		if(userInfo.getPassword().equals(CipherUtil.encrypt(oldPwd))){
			userInfo.setPassword(CipherUtil.encrypt(newPwd));
			int cnt = userInfoService.update(userInfo);
			result.setSuccess(cnt > 0);
		}else{
			result.setSuccess(false);
			result.setErrMsg("旧密码错误，如果忘记，请联系系统管理员。");
		}
		return result;
	}
	
	@RequestMapping(value = "level.do")
	@ResponseBody
	public List<UserInfo> level(@RequestParam(value = "roleid",required = true) int rid){
		Map<String,Object> params = new HashMap<>();
		Subject currentUser = SecurityUtils.getSubject();
		params.put("companyid",((UserInfo)currentUser.getSession().getAttribute("userInfo")).getCompanyid());
		params.put("roleid",rid);
		params.put("status",2);
		List<UserInfo> list = userInfoService.level(params);
		return list;
	}
	
	@RequestMapping(value = "duty3.do")
	@ResponseBody
	public List<UserInfo> duty3(@RequestParam(value = "projectitemid",required = true) int projectitemid){
		Map<String,Object> params = new HashMap<>();
		params.put("projectitemid",projectitemid);
		List<UserInfo> list = userInfoService.duty3(params);
		return list;
	}
	
	@RequestMapping(value = "/usertree.do")
	@ResponseBody
	public List<TreeNode> getUserTree(){
		List<TreeNode> nodes = new ArrayList<>();
		Subject currentUser = SecurityUtils.getSubject();
		Integer companyid = ((UserInfo)currentUser.getSession().getAttribute("userInfo")).getCompanyid();
		nodes = treeNodeService.findDepartment(companyid);
		for(TreeNode treeNode:nodes){
			if(treeNode.getChildren().size() > 0){
				treeNode.setState(TreeNode.STATE_OPEN);
			}else{
				treeNode.setState(TreeNode.STATE_CLOSED);
			}
		}
		return nodes;
	}
	
	@RequestMapping(value = "/usercompanytree.do")
	@ResponseBody
	public List<TreeNode> usercompanytree(){
		List<TreeNode> nodes = new ArrayList<>();
		nodes = treeNodeService.findCompany();
		for(TreeNode treeNode:nodes){
			if(treeNode.getChildren().size() > 0){
				treeNode.setState(TreeNode.STATE_OPEN);
			}else{
				treeNode.setState(TreeNode.STATE_CLOSED);
			}
		}
		return nodes;
	}
	
	@RequestMapping(value = "importExcel",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult importExcel(@RequestParam("excel") MultipartFile excel,HttpServletRequest request){
		OperateResult result = new OperateResult();
		ModelAndView modelAndView = new ModelAndView();
		try{
			Integer count = userInfoService.importExcel(excel,request);
			result.setSuccess(count > 0);
		}
		catch(Exception e){
			// TODO: handle exception
			modelAndView.addObject("msg",e.getMessage());
			result.setSuccess(false);
		}
		modelAndView.addObject("msg","数据导入成功");
		return result;
	}
}
